<template>
    <div class="article-list-edit">
        <div class="article-list-edit-card">
            <Row :gutter="25">
                <Col span="10">
                    <Form ref="formArticleData" :model="formArticleData" :rules="ruleArticleData" :label-width="80">
                        <FormItem label="是否显示">
                            <i-switch v-model="formArticleData.switch" size="large">
                                <span slot="open">显示</span>
                                <span slot="close">隐藏</span>
                            </i-switch>
                        </FormItem>
                        <FormItem label="文章标题" prop="title">
                            <Input v-model="formArticleData.title" placeholder="请输入文章标题"></Input>
                        </FormItem>
                        <FormItem label="分类" prop="type">
                            <Select :disabled="!!($route.query.isEdit)" v-model="formArticleData.type" placeholder="请选择分类">
                                <Option v-for="(key,value) in typeList" :value="key.catid">{{key.catname}}</Option>
                            </Select>
                        </FormItem>
                        <FormItem label="关键字" prop="font">
                            <Input v-model="formArticleData.font" placeholder="请输入关键字"></Input>
                        </FormItem>
                        <FormItem label="排序号"  prop="num">
                            <Input number v-model="formArticleData.num" placeholder="请输入排序号"></Input>
                        </FormItem>
                    </Form>
                </Col>
                <Col span="14">
                    <Row :gutter="10">
                        <Col span="12">
                            <Upload accept="image/png, image/jpeg, image/gif, image/jpg" type="drag" action="?" :before-upload="handleBeforeUpload">
                                <div class="upImg">
                                    <a><Icon type="ios-cloud-upload" size="52"></Icon></a>
                                    <p>点击或将图片拖拽到这里上传</p>
                                </div>
                            </Upload>
                        </Col>
                        <Col span="12" class="articleImgChange">
                            <img v-if="imgSrc!=''" :src="imgSrc"/>
                        </Col>
                    </Row>
                </Col>
            </Row>
            <textarea class='tinymce-textarea' id="tinymceEditer"></textarea>
            <div class="subCon">
                <Button type="primary" @click="handleSubmit">提交</Button>
                <Button @click="handleReset">重置</Button>
            </div>
        </div>
    </div>
</template>
<script>
    import tinymce from 'tinymce';
    export default {
        name:"article-list-edit",
        data(){
            const validateNum = (rule, value, callback) => {
                if (value==="") {
                    return callback(new Error('排序号不能为空'));
                }
                // 模拟异步验证效果
                setTimeout(() => {
                    if (!Number.isInteger(value)) {
                        callback(new Error('请输入数字值'));
                    } else {
                        callback();
                    }
                }, 1000);
            };
            return{
                typeList:[],//
                formArticleData:{
                    title:"",
                    type:"",
                    switch:true,//默认显示
                    font:"",
                    num:"",
                },
                ruleArticleData:{
                    title: [
                        { required: true, message: '文章标题不能为空', trigger: 'blur' }
                    ],
                    type: [
                        { required: true, message: '请选择分类', trigger: 'change' }
                    ],
                    font: [
                        { required: true, message: '请输入关键字', trigger: 'blur' }
                    ],
                    num: [
                        { required: true, validator: validateNum, trigger: 'blur' }
                    ]
                },
                content:"",
                imgSrc:"",//
                isBase64:false,
            }
        },
        mounted(){
            if(this.$route.query.isEdit){
                this.getEditCon()
            }else{
                this.init();
            }
            this.getArticleType()
        },
        methods:{
            getArticleType(){
                this.getJsonData("Articletype/getArticleType",{})
                    .then((res)=>{
                        this.typeList=res.data
                    })
            },
            //获取需要修改的信息
            getEditCon(){
                this.getJsonData("Articles/queryone",{articleId:this.$route.query.id})
                    .then((res)=>{
                        this.formArticleData.title=res.data.articletitle
                        this.formArticleData.switch=res.data.isshow==1?true:false
                        this.formArticleData.font=res.data.articlekey
                        this.content=res.data.articlecontent
                        this.formArticleData.type=res.data.catid
                        this.formArticleData.num=parseFloat(res.data.articlesort)
                        this.imgSrc=res.data.articleimg
                        this.init();
                    })
            },
            //提交
            handleSubmit () {
                this.$refs.formArticleData.validate((valid) => {
                    if (valid) {
                        if(this.imgSrc==""){
                            this.$Message.warning("请选择图片")
                        }else{
                            if(this.$route.query.isEdit){
                                if(this.isBase64){
                                    this.$Loading.start();
                                    this.upBaseImg("admin/upLoadImages",{image:this.imgSrc})
                                        .then((res) =>{
                                            this.editArticle(res.data.url)
                                        })
                                }else{
                                    this.$Loading.start();
                                    this.editArticle()
                                }
                            }else{
                                //新增方法
                                this.$Loading.start();
                                this.upBaseImg("admin/upLoadImages",{image:this.imgSrc})
                                    .then((res) =>{
                                        this.addArticle(res.data.url)
                                    })
                            }
                        }
                    }
                })
            },
            editArticle(url){
                this.getJsonData("Articles/updataArticles",{
                    articleId:this.$route.query.id,
                    articleTitle:this.formArticleData.title,
                    isShow:this.formArticleData.switch?1:-1,
                    articleContent:tinymce.get('tinymceEditer').getBody().innerHTML,
                    articleKey:this.formArticleData.font,
                    articleSort:this.formArticleData.num,
                    articleImg:this.isBase64?url:this.imgSrc,
                })
                    .then((res)=>{
                        this.$Message.success("修改成功")
                    })
            },
            addArticle(url){
                this.getJsonData("Articles/addArticles",{
                    articleTitle:this.formArticleData.title,
                    isShow:this.formArticleData.switch?1:-1,
                    articleContent:tinymce.get('tinymceEditer').getBody().innerHTML,
                    articleKey:this.formArticleData.font,
                    articleSort:this.formArticleData.num,
                    catId:this.formArticleData.type,
                    articleImg:url,
                    })
                    .then((res)=>{
                        this.$Message.success("新增成功")
                    })
            },
            //重置
            handleReset () {
                this.$refs.formArticleData.resetFields();
            },
            //初始化方法
            init () {
                this.$nextTick(() => {
                    let vm = this;
                    let height = document.body.offsetHeight - 600;
                    tinymce.init({
                        selector: '#tinymceEditer',
                        branding: false,
                        elementpath: false,
                        height: height,
                        language: 'zh_CN.GB2312',
                        menubar: 'edit insert view format table tools',
                        plugins: [
                            'advlist autolink lists link image charmap print preview hr anchor pagebreak imagetools',
                            'searchreplace visualblocks visualchars code fullpage',
                            'insertdatetime media nonbreaking save table contextmenu directionality',
                            'emoticons paste textcolor colorpicker textpattern imagetools codesample'
                        ],
                        toolbar1: ' newnote print preview | undo redo | insert | styleselect | forecolor backcolor bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image emoticons media codesample',
                        autosave_interval: '20s',
                        image_advtab: true,
                        table_default_styles: {
                            width: '100%',
                            borderCollapse: 'collapse'
                        },
                        setup: function (editor) {
                            editor.on('init', function (e) {
                                vm.spinShow = false;
                                tinymce.get('tinymceEditer').setContent(vm.content);//赋值内容
                            });
                            editor.on('keydown', function (e) {
                                /*localStorage.editorContent = tinymce.get('tinymceEditer').getContent();*/
                            });
                        }
                    });
                });
            },
            handleBeforeUpload(file){
                if((Math.round(file.size/1024*100)/100)<2000){
                    this.caijianImg(file)
                }else{
                    this.$Notice.error({
                        title: '文件过大',
                        desc: '文件 '+file.name +'/'+(Math.round(file.size/1024*100)/100)+'KB'+'，请上传 2M 以内的图片。',
                        duration:4.5
                    });
                }
                //禁止默认上传
                return false
            },
            caijianImg(file){
                let reader = new FileReader();
                reader.onload = () => {
                    this.imgSrc=reader.result
                    this.isBase64=true
                    reader.onload = null;
                };
                reader.readAsDataURL(file);
            }
        },
        //销毁初始化
        destroyed () {
            tinymce.get('tinymceEditer').destroy();
        }
    }
</script>
<style lang="less">
    @import "./article-list-edit";
</style>